import utils from "@/common/utils";
export default {
  // 将图片转化为base64
  fileToBase64: (file, callback) => {
    const result = file.target ? file.target.files[0] : file;
    try {
      const reader = new FileReader(); // 转base64
      reader.readAsDataURL(result);
      reader.onload = (e) => {
        // const base64 = e.target.result;
        callback(e);
      };
    } catch (e) {
      console.log(e.message);
    }
  },
  /**
   * 图片旋转
   * @param {*} src base64
   * @param {*} edg 旋转角度
   * @param {*} callback
   */
  rotateBase64Img: (src, edg, callback) => {
    const canvas = document.createElement("canvas");
    const ctx = canvas.getContext("2d");
    let imgW; // 图片宽度
    let imgH; // 图片高度
    let size; // canvas初始大小
    if (edg % 90 !== 0) {
      console.error("旋转角度必须是90的倍数!");
      // throw "旋转角度必须是90的倍数!";
    }
    edg < 0 && (edg = (edg % 360) + 360);
    const quadrant = (edg / 90) % 4; // 旋转象限
    const cutCoor = { sx: 0, sy: 0, ex: 0, ey: 0 }; // 裁剪坐标
    const image = new Image();
    image.crossOrigin = "anonymous";
    image.src = src;
    image.onload = function () {
      imgW = image.width;
      imgH = image.height;
      size = imgW > imgH ? imgW : imgH;
      canvas.width = size * 2;
      canvas.height = size * 2;
      switch (quadrant) {
        case 0:
          cutCoor.sx = size;
          cutCoor.sy = size;
          cutCoor.ex = size + imgW;
          cutCoor.ey = size + imgH;
          break;
        case 1:
          cutCoor.sx = size - imgH;
          cutCoor.sy = size;
          cutCoor.ex = size;
          cutCoor.ey = size + imgW;
          break;
        case 2:
          cutCoor.sx = size - imgW;
          cutCoor.sy = size - imgH;
          cutCoor.ex = size;
          cutCoor.ey = size;
          break;
        case 3:
          cutCoor.sx = size;
          cutCoor.sy = size - imgW;
          cutCoor.ex = size + imgH;
          cutCoor.ey = size + imgW;
          break;
      }
      ctx.translate(size, size);
      ctx.rotate((edg * Math.PI) / 180);
      ctx.drawImage(image, 0, 0);
      const imgData = ctx.getImageData(
        cutCoor.sx,
        cutCoor.sy,
        cutCoor.ex,
        cutCoor.ey
      );
      if (quadrant % 2 === 0) {
        canvas.width = imgW;
        canvas.height = imgH;
      } else {
        canvas.width = imgH;
        canvas.height = imgW;
      }
      ctx.putImageData(imgData, 0, 0);
      callback(canvas.toDataURL());
    };
  },

  /**
   * 将图片转化为base64
   * @param {Object} // target 目标DOM
   * @param {Function} // callback 回调
   * @param {Boolean} // isCompress 控制是否压缩
   * @param {Number} // size 当前图片size大小
   * @param {Boolean} // watermark 标记当前图片是否需要添加水印，不需要只为false
   * @param {Boolean} // watermarkUrl 水印对应的静态图片url，没有则为'null'
   */
  fileBlobToBase64: function (
    target,
    callback,
    params: {
      isCompress;
      size;
      watermark;
      watermarkUrl;
    }
  ) {
    const reader = new FileReader();
    reader.readAsDataURL(target);
    const isIos = utils.exenv.IS_IOS;
    reader.onload = (e) => {
      // 如果需要加水印，则统一走dealImage方法，通过canvas添加水印，如果不需要，再走下面的逻辑
      if (params.watermark) {
        this.dealImage(e.target.result, 700, callback, params.watermarkUrl);
        return false;
      }
      // isIos && size > 1：ios端大于1M就进行处理，处理ios上传图片翻转问题
      if (params.isCompress || (isIos && params.size > 1)) {
        this.dealImage(e.target.result, 700, callback, params.watermarkUrl);
      } else {
        // 小于1M不压缩，直接上传
        callback(e.target.result);
      }
    };
    reader.readAsDataURL(target);
  },
  /**
   * 压缩base64
   * @param {String} base64
   * @param {Number} w
   * @param {Function} callback
   * @param {String} watermarkUrl // 水印对应的url
   */
  dealImage: function (base64, w, callback, watermarkUrl) {
    const newImage = document.createElement("img");
    let quality = 0.4; // 压缩系数0-1之间
    newImage.src = base64;
    newImage.setAttribute("crossOrigin", "Anonymous"); // url为外域时需要
    let imgWidth, imgHeight;
    newImage.onload = (e) => {
      const orient = this.getPhotoOrientation(e.target);
      const target: any = e.target;
      imgWidth = newImage.width;
      imgHeight = newImage.height;
      const canvas = document.createElement("canvas");
      const ctx = canvas.getContext("2d");
      if (Math.max(imgWidth, imgHeight) > w) {
        if (imgWidth > imgHeight) {
          canvas.width = w;
          canvas.height = (w * imgHeight) / imgWidth;
        } else {
          canvas.height = w;
          canvas.width = (w * imgWidth) / imgHeight;
        }
      } else {
        canvas.width = imgWidth;
        canvas.height = imgHeight;
        quality = 0.4;
      }
      if (orient === 6) {
        // orient为6时，说明时ios上传，图片会在上传时发生旋转，需做特殊处理
        canvas.width = newImage.height * 0.5;
        canvas.height = newImage.width * 0.5;
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        ctx.translate(canvas.width / 2, canvas.height / 2);
        ctx.rotate((90 * Math.PI) / 180);
        ctx.drawImage(
          target,
          0 - canvas.height / 2,
          0 - canvas.width / 2,
          canvas.height,
          canvas.width
        );
        quality = 0.2;
      } else {
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        ctx.drawImage(target, 0, 0, canvas.width, canvas.height);
      }
      if (watermarkUrl) {
        // 需要添加水印
        const watermarkImg = document.createElement("img");
        watermarkImg.src = watermarkUrl;
        watermarkImg.onload = function (e) {
          const proportion = watermarkImg.height / watermarkImg.width;
          const waterWidth = canvas.width * 0.5;
          const waterHight = waterWidth * proportion;
          ctx.drawImage(
            target,
            canvas.width / 2 - waterWidth / 2, // 水印水平居中显示
            canvas.height / 2 - waterHight / 2, // 水印垂直居中显示
            waterWidth,
            waterHight
          );
          const base64 = canvas.toDataURL("image/jpeg", quality); // 压缩语句
          callback(base64); // 必须通过回调函数返回，否则无法及时拿到该值
        };
      } else {
        let base64 = canvas.toDataURL("image/jpeg", quality); // 压缩语句
        // 如想确保图片压缩到自己想要的尺寸,如要求在50-150kb之间，请加以下语句，quality初始值根据情况自定
        while (base64.length / 1024 > 150) {
          quality -= 0.01;
          base64 = canvas.toDataURL("image/jpeg", quality);
        }
        // 防止最后一次压缩低于最低尺寸，只要quality递减合理，无需考虑
        while (base64.length / 1024 < 50) {
          quality += 0.001;
          base64 = canvas.toDataURL("image/jpeg", quality);
        }
        callback(base64); // 必须通过回调函数返回，否则无法及时拿到该值
      }
    };
  },
  /**
   * 获取文件大小，单位M
   */
  geFileSize: function (fileData) {
    let size = 0;
    if (fileData) {
      size = fileData.size;
    }
    return size / 1000000;
  },
  /**
   * 校验文件是否超过允许值
   * @param fileData
   * @param maxSize 最大值
   */
  testMaxSize: function (fileData, maxSize) {
    let isAllow = false;
    const size = fileData.size;
    isAllow = size <= maxSize;
    if (!isAllow) {
      return false;
    }
    return isAllow;
  },
  /**
   * 判断图片类型
   * @param name
   * @param gif|jpg|jpeg|png|GIF|JPG|PNG
   */
  testImgType: function (name) {
    if (!/\.(jpg|jpeg|png|JPG|PNG)$/.test(name)) {
      return false;
    }
    return true;
  },
  // 通过url地址获取图片的详细信息，包括宽高
  imgLoad: (url, callback) => {
    const img = new Image();
    img.src = url;
    if (img.complete) {
      // complete 属性可返回浏览器是否已完成对图像的加载。
      callback(img);
    } else {
      img.onload = function () {
        callback(img);
        img.onload = null;
      };
    }
  },

  // base64 转file(压缩图片完成后最后一步)
  imgToBase64: (
    base64File,
    params = {
      format: "png",
    }
  ) => {
    const arr = base64File.split(",");
    const mime = arr[0].match(/:(.*?);/)[1]; // 转成blob
    const bstr = atob(arr[1]);
    let n = bstr.length;
    const u8arr = new Uint8Array(n);
    while (n--) {
      u8arr[n] = bstr.charCodeAt(n);
    }
    return new window.File(
      [new Blob([u8arr], { type: mime })],
      `${new Date().getTime()}.${params.format}`,
      { type: "image/jpeg" }
    ); // 转成file
  },
};
